package com.ys.timer;

import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.entity.eKnowAi.EKnowTimerSet;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;
import com.ys.service.eKnowAi.EKnowTimerSetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 逸知道AI知识库相关定时器
 */
@Controller
public class TimerEknowKnowledgeBaseDaily {
	private static final Logger logger = LoggerFactory.getLogger(TimerEknowKnowledgeBaseDaily.class);

	@Autowired
	private EKnowKnowledgeListService eKnowKnowledgeListService;

	@Autowired
	private EKnowTimerSetService eKnowTimerSetService;

	//定时更新知识库-物流拼票
	//@Scheduled(cron = "0 */30 * * * ?")//间隔30分钟执行一次
	public void addTpAnalysisDailyTargetSetByShop() {
		try {
			logger.info("***********每日定时更新知识库-物流拼票，开始***********");
			String timeKey = "logisticsTicket";
			//知识库分类配置信息
			EKnowTimerSet eKnowTimerSet = new EKnowTimerSet().setTimerKey(timeKey).queryFirst();
			//旧数据
			List<EKnowKnowledgeList> eKnowKnowledgeListOld = new EKnowKnowledgeList().setInfoMark(timeKey).setOrderby("A.Id").queryList();
			//物流方式信息
			List<Map<String, Object>> countLogisticsTicketGroupByName = eKnowTimerSetService.countLogisticsTicketGroupByCountry();
			//整理统计后的信息
			List<Map<String, Object>> getLogisticsTicketByCount = eKnowTimerSetService.getLogisticsTicketByCount(countLogisticsTicketGroupByName);
			//国家数据
			List<String> countryList = eKnowTimerSetService.getCountryList();
			if(getLogisticsTicketByCount!=null && getLogisticsTicketByCount.size()>0 && eKnowTimerSet!=null){

				//新增 或 修改
				if(eKnowKnowledgeListOld!=null && eKnowKnowledgeListOld.size()>0){

					for(String countryItem:countryList){
						String sectionId = timeKey+"_"+countryItem;
						List<String> informationList = new ArrayList<>();
						List<Map<String, Object>> newListByCountry = getLogisticsTicketByCount.stream().filter(item->item.get("sectionId").equals(sectionId)).collect(Collectors.toList());
						List<EKnowKnowledgeList> oldListByCountry = eKnowKnowledgeListOld.stream().filter(item->item.getSectionId().equals(sectionId)).collect(Collectors.toList());
						if(newListByCountry.size()>0){
							for(int i=0;i<newListByCountry.size();i++){
								boolean isAdd = true;
								boolean isDel = true;
								if(oldListByCountry.size()>i){
									if(newListByCountry.get(i).get("information").toString().equals(oldListByCountry.get(i).getInformation())){
										//若资料信息不变，则无需变更
										isAdd = false;
										isDel = false;
									}
								}else {
									isDel = false;
								}
								if(isDel){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
								if(isAdd){//新增向量数据库
									informationList.add(newListByCountry.get(i).get("information").toString());
								}
							}
							//删除多余的信息
							if(oldListByCountry.size()>newListByCountry.size()){
								for(int i=newListByCountry.size();i<oldListByCountry.size();i++){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
							}
						}else {
							if(oldListByCountry.size()>0){
								for(int i=0;i<oldListByCountry.size();i++){
									//删除
									eKnowKnowledgeListService.deleteKnowledgeListWithES(oldListByCountry.get(i).getId());
								}
							}
						}
						List<String> informationListNew = eKnowKnowledgeListService.replaceSpace(informationList);
						eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationListNew,sectionId,timeKey,"admin");
					}


					/*旧的方案，按物流方式进行分段，直接根据分段判断是否新增；新的改成按各个物流方式所在的国家进行分段
					for(Map<String, Object> markItem:countLogisticsTicketGroupByName){
						String nameLogsticsWay = markItem.get("nameLogsticsWay").toString();
						List<Map<String, Object>> newListByWay = getLogisticsTicketByCount.stream().filter(item->item.get("sectionId").equals(timeKey+"_"+nameLogsticsWay)).collect(Collectors.toList());
						List<EKnowKnowledgeList> oldListByWay = eKnowKnowledgeListOld.stream().filter(item->item.getSectionId().equals(timeKey+"_"+nameLogsticsWay)).collect(Collectors.toList());
						if(newListByWay.size()>0 && oldListByWay.size()==newListByWay.size()){//数量不变，只修改系统知识库
							for(int i=0;i<oldListByWay.size();i++){
								EKnowKnowledgeList eKnowKnowledgeList = oldListByWay.get(i);
								eKnowKnowledgeList.setInformation(newListByWay.get(i).get("information").toString());
								eKnowKnowledgeListService.updateKnowledgeList(eKnowKnowledgeList);
							}
						}else {//数量变更，同时修改向量数据库
							//删除
							for(EKnowKnowledgeList item:oldListByWay){
								eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
							}
							//新增
							addTimerListByNameAndNew(timeKey,newListByWay,eKnowTimerSet,nameLogsticsWay);
						}
					}

					 */
				}else {//从未添加过
					//addTimerListByNew(timeKey,getLogisticsTicketByCount,eKnowTimerSet,countLogisticsTicketGroupByName);for(String countryItem:countryList){
					for(String countryItem:countryList){
						addTimerListByNameAndNew(timeKey,getLogisticsTicketByCount,eKnowTimerSet,countryItem);
					}
				}
			}else {
				if(eKnowKnowledgeListOld!=null && eKnowKnowledgeListOld.size()>0){
					//删除
					for(EKnowKnowledgeList item:eKnowKnowledgeListOld){
						eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
					}
				}
			}
			logger.info("***********每日定时更新知识库-物流拼票，完成***********");
		}catch (Exception e){
			logger.error("定时更新知识库-物流拼票出错：",e.getMessage(),e);
		}
	}


	//定时更新知识库、向量数据库-物流拼票
	//@Scheduled(cron = "0 0 4 * * ?")//每天4点触发任务
	public void updateTpAnalysisDailyTargetSetByShopWithES() {
		try {
			logger.info("***********每日定时更新向量数据库-物流拼票，开始***********");
			String timeKey = "logisticsTicket";
			List<EKnowKnowledgeList> oldList = new EKnowKnowledgeList().setInfoMark(timeKey).queryList();
			//物流方式信息
			List<Map<String, Object>> countLogisticsTicketGroupByName = eKnowTimerSetService.countLogisticsTicketGroupByCountry();
			//整理统计后的信息
			List<Map<String, Object>> newList = eKnowTimerSetService.getLogisticsTicketByCount(countLogisticsTicketGroupByName);
			//处理
			addTimerListByOld(timeKey,oldList,newList);
			logger.info("***********每日定时更新向量数据库-物流拼票，完成***********");
		}catch (Exception e){
			logger.error("定时更新知识库-物流拼票出错：",e.getMessage(),e);
		}
	}


	//新增知识库信息 根据物流方式
	public void addTimerListByNameAndNew(String timeKey,List<Map<String, Object>> getLogisticsTicketByCount,
								  EKnowTimerSet eKnowTimerSet,String nameLogsticsWay) throws Exception{
		List<Map<String, Object>> newList = getLogisticsTicketByCount.stream().filter(item->item.get("sectionId").equals(timeKey+"_"+nameLogsticsWay)).collect(Collectors.toList());
		List<String> informationList = new ArrayList<>();
		for(Map<String, Object> item:newList){
			informationList.add(item.get("information").toString());
		}
		eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationList,timeKey+"_"+nameLogsticsWay,timeKey,"admin");
	}


	//根据知识库信息，删除后新增
	public void addTimerListByOld(String timeKey,List<EKnowKnowledgeList> oldList,List<Map<String, Object>> newList) throws Exception{
		if(oldList!=null && oldList.size()>0){
			//删除
			for(EKnowKnowledgeList item:oldList){
				eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
			}
		}
		//新增
		EKnowTimerSet eKnowTimerSet = new EKnowTimerSet().setTimerKey(timeKey).queryFirst();
		if(eKnowTimerSet!=null && newList!=null && newList.size()>0 ){
			for(Map<String, Object> markItem:newList){
				List<String> informationList = new ArrayList<>();
				String sectionId = markItem.get("sectionId").toString();
				informationList.add(markItem.get("information").toString());
				eKnowKnowledgeListService.addKnowledgeListByList3(eKnowTimerSet.getBaseId(),eKnowTimerSet.getTypeId(),informationList,sectionId,timeKey,"admin");
			}
		}
	}






}
